package com.ygqh.baby.handler;

import com.alibaba.fastjson.JSON;
import com.mumu.commons.utils.StringUtils;
import com.ygqh.baby.ao.ResponseEntity;
import com.ygqh.baby.redis.RedisDao;
import com.ygqh.baby.utils.DateConvertUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Component
public class HolidayNoticeHandler {

    private static final String HOLIDAY_NOTICE_KEY = "HOLIDAY_NOTICE";

    @Autowired
    private RedisDao redisDao;

    public ResponseEntity setHolidayNotice(String imgUrl, Date startDate, Date endDate, String handler) {
        Map<String, Object> map = new HashMap<>();
        map.put("imgUrl", imgUrl);
        map.put("startDate", startDate);
        map.put("endDate", endDate);
        map.put("updateTime", new Date());
        map.put("updateBy", handler);
        redisDao.set(HOLIDAY_NOTICE_KEY, JSON.toJSONString(map), 0);

        return ResponseEntity.success();
    }

    public ResponseEntity delHolidayNotice() {
        redisDao.del(HOLIDAY_NOTICE_KEY);
        return ResponseEntity.success();
    }

    public Map getHolidayNotice(boolean checkDate) {
        String s = redisDao.get(HOLIDAY_NOTICE_KEY);
        if (StringUtils.isNotBlank(s)) {
            Map map = JSON.parseObject(s, Map.class);
            if (checkDate) {
                long start = (long) map.get("startDate");
                long end = (long) map.get("endDate");
                Date startDate = new Date(start);
                Date endDate = new Date(end);
                Date now = new Date();
                if (now.after(startDate) && now.before(DateConvertUtils.getDateEnd(endDate))) {
                    return map;
                }
            }
            return map;
        }
        return new HashMap();
    }

    public String getHolidayNoticeImgUrl(boolean checkDate) {
        Map holidayNotice = getHolidayNotice(checkDate);

        return (String) holidayNotice.get("imgUrl");
    }

}
